package demo3;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-08-08
 * Time: 15:42
 */
public class TcpEchoServer {
    private ServerSocket socket = null;

    public TcpEchoServer(int port) throws IOException {
        socket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            Socket clientserver = socket.accept();
            Thread thread = new Thread(() -> {
                try {
                    processConnection(clientserver);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            thread.start();
            //processConnection(clientserver);
        }
    }

    public void processConnection(Socket clientserver) throws IOException {
        System.out.printf("[%s: %d] 客户端上线\n", clientserver.getInetAddress().toString(), clientserver.getPort());
        try (InputStream inputStream = clientserver.getInputStream();
             OutputStream outputStream = clientserver.getOutputStream()){

            while (true){
                Scanner scanner = new Scanner(inputStream);
                if (!scanner.hasNext()){
                    System.out.printf("[%s: %d] 客户端下线\n", clientserver.getInetAddress().toString(), clientserver.getPort());
                    break;
                }
                String request = scanner.next();
                String response = process(request);
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s: %d] req: %s, res: %s\n", clientserver.getInetAddress().toString(), clientserver.getPort(),
                        request, response);
            }

        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            clientserver.close();
        }
    }

    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }


}
